<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理系统 - 管理员控制台</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Noto Sans SC', Arial, sans-serif;
            background: linear-gradient(135deg, #f6f9fc 0%, #eef2f7 100%);
            min-height: 100vh;
        }
        .header {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            color: white;
            padding: 1.2rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .header h1 {
            margin: 0;
            font-size: 1.5rem;
            font-weight: 700;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 1.5rem;
        }
        .user-info span {
            font-weight: 500;
        }
        .logout-btn {
            background-color: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 0.6rem 1.2rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        .logout-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
            transform: translateY(-1px);
        }
        .main-content {
            max-width: 1400px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .action-bar {
            display: flex;
            gap: 1.5rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        .add-book-btn {
            padding: 0.8rem 2rem;
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .add-book-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2);
        }
        .search-bar {
            display: flex;
            gap: 1rem;
            flex: 1;
            min-width: 300px;
        }
        .search-input {
            flex: 1;
            padding: 0.8rem 1.2rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background-color: white;
        }
        .search-input:focus {
            outline: none;
            border-color: #2ecc71;
            box-shadow: 0 0 0 3px rgba(46, 204, 113, 0.1);
        }
        .search-btn {
            padding: 0.8rem 2rem;
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        .search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2);
        }
        .book-list {
            background-color: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        .book-table {
            width: 100%;
            border-collapse: collapse;
        }
        .book-table th,
        .book-table td {
            padding: 1.2rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        .book-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
            white-space: nowrap;
        }
        .book-table tr:hover {
            background-color: #f8f9fa;
        }
        .book-table td {
            color: #34495e;
        }
        .action-btn {
            padding: 0.6rem 1.2rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 0.5rem;
            font-weight: 500;
        }
        .edit-btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
        }
        .edit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
        }
        .remove-btn {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
        }
        .remove-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.2);
        }
        .status-badge {
            padding: 0.4rem 0.8rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            display: inline-block;
        }
        .status-available {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
        .status-unavailable {
            background-color: #ffebee;
            color: #c62828;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 2rem;
        }
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #2ecc71;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .no-results {
            text-align: center;
            padding: 3rem;
            color: #7f8c8d;
            font-size: 1.1rem;
        }
        @media (max-width: 1200px) {
            .main-content {
                padding: 0 1rem;
            }
            .book-table {
                display: block;
                overflow-x: auto;
            }
        }
        @media (max-width: 768px) {
            .header {
                padding: 1rem;
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            .action-bar {
                flex-direction: column;
            }
            .search-bar {
                width: 100%;
            }
            .add-book-btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>图书管理系统 - 管理员控制台</h1>
        <div class="user-info">
            <span id="username"></span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="main-content">
        <div class="action-bar">
            <button class="add-book-btn" onclick="location.href='addBook.html'">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M12 5v14M5 12h14"/>
                </svg>
                添加图书
            </button>
            <div class="search-bar">
                <input type="text" class="search-input" placeholder="搜索图书..." id="searchInput" onkeypress="handleKeyPress(event)">
                <button class="search-btn" onclick="searchBooks()">搜索</button>
            </div>
        </div>

        <div class="book-list">
            <table class="book-table">
                <thead>
                    <tr>
                        <th>书名</th>
                        <th>作者</th>
                        <th>ISBN</th>
                        <th>出版社</th>
                        <th>出版日期</th>
                        <th>分类</th>
                        <th>总数量</th>
                        <th>可借数量</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="bookList">
                    <!-- 图书列表将通过JavaScript动态加载 -->
                </tbody>
            </table>
            <div id="loading" class="loading">
                <div class="loading-spinner"></div>
            </div>
            <div id="noResults" class="no-results" style="display: none;">
                没有找到相关图书
            </div>
        </div>
    </div>

    <script>
        // 检查登录状态
        function checkLogin() {
            fetch('../checkLogin')
                .then(response => response.json())
                .then(data => {
                    if (!data.loggedIn || data.role !== 'admin') {
                        window.location.href = 'login.html';
                    } else {
                        document.getElementById('username').textContent = data.username;
                        fetchBooks();
                    }
                })
                .catch(error => {
                    console.error('Error checking login status:', error);
                    window.location.href = 'login.html';
                });
        }

        function fetchBooks(searchTerm = '') {
            const bookListDiv = document.getElementById('bookList');
            bookListDiv.innerHTML = '<div class="loading"><div class="loading-spinner"></div><p>加载中...</p></div>';
            const loadingDiv = bookListDiv.querySelector('.loading');
            loadingDiv.style.display = 'block';

            let url = '../admin/book';
            if (searchTerm) {
                url += `?q=${encodeURIComponent(searchTerm)}`;
            }
            
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络错误或服务器返回错误');
                    }
                    return response.json();
                })
                .then(books => {
                    loadingDiv.style.display = 'none';
                    renderBooks(books);
                })
                .catch(error => {
                    loadingDiv.style.display = 'none';
                    console.error('获取图书列表失败:', error);
                    bookListDiv.innerHTML = '<p class="no-results">加载图书失败，请稍后重试。</p>';
                });
        }

        function renderBooks(books) {
            const bookListDiv = document.getElementById('bookList');
            if (books.length === 0) {
                bookListDiv.innerHTML = '<p class="no-results">没有找到相关图书。</p>';
                return;
            }

            let tableHtml = `
                <table class="book-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>标题</th>
                            <th>作者</th>
                            <th>ISBN</th>
                            <th>出版社</th>
                            <th>出版日期</th>
                            <th>分类</th>
                            <th>总份数</th>
                            <th>可用份数</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            books.forEach(book => {
                let statusText = '';
                let statusClass = '';
                if (book.status === 'active') {
                    statusText = '已上架';
                    statusClass = 'status-available';
                } else if (book.status === 'pending_review') {
                    statusText = '待审核';
                    statusClass = 'status-unavailable'; // 可以考虑新的颜色或警告色
                } else if (book.status === 'removed') {
                    statusText = '已移除';
                    statusClass = 'status-unavailable'; // 可以考虑新的颜色或警告色
                }

                tableHtml += `
                    <tr>
                        <td>${book.id}</td>
                        <td>${book.title}</td>
                        <td>${book.author}</td>
                        <td>${book.isbn}</td>
                        <td>${book.publisher}</td>
                        <td>${book.publish_date}</td>
                        <td>${book.category}</td>
                        <td>${book.total_copies}</td>
                        <td>${book.available_copies}</td>
                        <td><span class="status-badge ${statusClass}">${statusText}</span></td>
                        <td>
                `;
                
                if (book.status === 'pending_review') {
                    tableHtml += `
                            <button class="action-btn edit-btn" onclick="approveBook(${book.id})">批准上架</button>
                            <button class="action-btn remove-btn" onclick="removeBook(${book.id})">删除</button>
                    `;
                } else if (book.status === 'active') {
                    tableHtml += `
                            <button class="action-btn remove-btn" onclick="removeBook(${book.id})">下架</button>
                    `;
                }
                // For 'removed' status, no action buttons might be desired, or perhaps a 'restore' button.
                // For now, no buttons for 'removed' status.

                tableHtml += `
                        </td>
                    </tr>
                `;
            });

            tableHtml += `
                    </tbody>
                </table>
            `;
            bookListDiv.innerHTML = tableHtml;
        }

        function approveBook(bookId) {
            if (!confirm('确定要批准这本书上架吗？')) {
                return;
            }
            
            fetch(`../admin/book/${bookId}/approve`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (response.ok) {
                    alert('图书已成功批准上架！');
                    fetchBooks(); // 重新加载图书列表
                } else {
                    response.json().then(error => {
                        alert('批准上架失败: ' + (error.message || '未知错误'));
                    }).catch(() => {
                        alert('批准上架失败，服务器返回未知错误。');
                    });
                }
            })
            .catch(error => {
                console.error('批准上架时发生网络错误:', error);
                alert('批准上架时发生网络错误。');
            });
        }

        function removeBook(bookId) {
            if (!confirm('确定要删除或下架这本书吗？此操作不可逆！')) {
                return;
            }

            fetch(`../admin/book/${bookId}`, {
                method: 'DELETE'
            })
            .then(response => {
                if (response.ok) {
                    alert('图书已成功删除或下架！');
                    fetchBooks(); // 重新加载图书列表
                } else {
                    response.json().then(error => {
                        alert('删除/下架失败: ' + (error.message || '未知错误'));
                    }).catch(() => {
                        alert('删除/下架失败，服务器返回未知错误。');
                    });
                }
            })
            .catch(error => {
                console.error('删除/下架时发生网络错误:', error);
                alert('删除/下架时发生网络错误。');
            });
        }

        // 搜索图书
        function searchBooks() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            if (!searchTerm) {
                fetchBooks();
                return;
            }

            fetchBooks(searchTerm);
        }

        // 处理回车键搜索
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                searchBooks();
            }
        }

        // 退出登录
        function logout() {
            fetch('../logout', {
                method: 'POST'
            })
            .then(() => {
                window.location.href = 'login.html';
            })
            .catch(error => {
                console.error('Error logging out:', error);
                window.location.href = 'login.html';
            });
        }

        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', checkLogin);
    </script>
</body>
</html> 